<template>
  <div class="NormalChart" v-if="normalData">
    <div class="chart">
      <div id="chart" style="height:50vh;width: 100%"></div>
    </div>
    <div class="total">
      <div class="item">
        <label>样本数：</label><span>{{ normalData.count }}</span>
      </div>
      <div class="item">
        <label>最大值：</label><span>{{ normalData.maxiMum }}</span>
      </div>
      <div class="item">
        <label>最小值：</label><span>{{ normalData.miniMum }}</span>
      </div>
      <div class="item">
        <label>平均值：</label><span>{{ normalData.median }}</span>
      </div>      
      <div class="item">
        <label>cp：</label><span>{{ normalData.cp }}</span>
      </div>      
      <div class="item">
        <label>cpk：</label><span>{{ normalData.cpk }}</span>
      </div>
      <div class="item">
        <label>cpl：</label><span>{{ normalData.cpl }}</span>
      </div>
      <div class="item">
        <label>cpu：</label><span>{{ normalData.cpu }}</span>
      </div>
      <div class="item">
        <label>sigma：</label><span>{{ normalData.sigma }}</span>
      </div>
      <div class="item">
        <label>clx：</label><span>{{ normalData.clX }}</span>
      </div>
    </div>
  </div>
</template>

<script>
let echarts = require('echarts')

export default {
  name: 'ControlChart',
  components: {
  },
  props: {
    normalData: {
      type: [Object, null]
    },
    x_count: {
      type: Number,
      default: 100
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    normalData: {
      deep: true,
      immediate: true,
      handler (val) {
        if(!val) return
        this.chartInit()
      }
    }
  },
  created() {
    console.log('初始化')
  },
  mounted() {
    // window.addEventListener('resize', this.handleWindowResize)
    window.addEventListener('resize', this.resize)
  },
  computed: {
    bar_data () {
      if(!this.normalData) return []
      if(!this.xAxisData.length) return []
      let data = new Map()
      for(let row of this.normalData.controlValues) {
        let index = [0, ...this.xAxisData].findIndex(val => val >= row.value)
        let key = Number(((this.xAxisData[index] + this.xAxisData[index - 1]) / 2).toFixed(6))
        data.set(key, (data.get(key) || 0) + 1) 
      }
      return data
    },
    line_data () {
      if(!this.normalData) return []
      if(!this.xAxisData.length) return []
      let data = new Map()
      for(let row of this.normalData.controlValues) {
        data.set(row.value, [row.value, this.fx(this.normalData.sigma, row.value, this.normalData.clX)])
      }
      return [...data.values()]
      // let array= this.normalData.controlValues.map(v => v.value * 1000)
      // let mean=(array.reduce((a,b)=>a+b))/array.length;    
      // // 方差    
      // let variance = array.map(x=>{      
      //     return Math.pow(x-mean,2);    
      //   }).reduce((a,b)=>a+b)/array.length;    
      // // 标准差    
      // let StandardDeviation = Math.sqrt(variance);    
      // let convertedData=[];    
      // for(let x=mean-3*StandardDeviation;x<=mean + 3*StandardDeviation;x++){      
      //     let y=1/(StandardDeviation*Math.sqrt(2*(Math.PI)))*Math.exp(-(Math.pow(x-mean,2))/(2*(Math.pow(StandardDeviation,2))));      
      //     convertedData.push([x / 1000,y]);   
      // }    
      // return convertedData
    },
    xAxisMinData () {
      return this.normalData ? this.normalData.lsl - this.normalData.lsl * 0.1 : 0
    },
    xAxisMaxData () {
      return this.normalData ? this.normalData.usl + this.normalData.usl * 0.1 : 0
    },
    xAxisData () {
      return Array.from({length: this.x_count + 1}, (v,i) => {
          return Number((((this.xAxisMaxData - this.xAxisMinData) / this.x_count) * i + this.xAxisMinData).toFixed(6))
      })
    },
    option () {
      return {
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 0.8)',
          position: 'left'
        },
        legend: {
          show: true,
          data: [{
              name: 'line'
          },{
              name: '区间点数'
          },{
              name: '正态分布'
          }]
        },
        title: {
          left: 'left',
          text: 'Normal distribution'
        },
        grid: {
          left: '4%',
          right: '6%'
        },
        xAxis: {
          type: 'value',
          data: this.xAxisData,
          nameLocation: 'middle',
          //interval: 50,
          boundaryGap: false,
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {
            color: '#000',
            interval: 0,
            fontSize: 12,
            rotate:25
          },
          // axisLabel: {
          //   rotate: -45
          // },
          splitLine: {
            show: false
          },
          min: Number(this.xAxisMinData.toFixed(4)),
          max: Number(this.xAxisMaxData.toFixed(4)),
          interval: Number(((this.xAxisMaxData - this.xAxisMinData) / this.x_count).toFixed(5))
        },
        yAxis: [
          {
            type: 'value',
            boundaryGap: [0, '100%'],
            splitLine: {
              show: false
            },
            max: (value) => {
              return value.max;
            }
          },
          {
            type: 'value',
            boundaryGap: [0, '100%'],
            splitLine: {
              show: false
            },
            max: (value) => {
                return Math.ceil(value.max * 1000) / 1000;
            },
            splitNumber: 2
          }
        ],
        dataZoom: [
          {
            type: 'inside',
            startValue: (this.normalData.lsl < this.normalData.miniMum ? this.normalData.lsl : this.normalData.maxiMum) - 0.02,
            endValue: (this.normalData.usl > this.normalData.maxiMum ? this.normalData.usl : this.normalData.maxiMum) + 0.02,

          }
        ],
        series: [
          {
            name: '区间点数',
            type: 'bar',
            yAxisIndex: 0,
            xAxisIndex: 0,
            barCategoryGap: "0%",
            showBackground: false,
            data: [...this.bar_data]
          },
          {
            yAxisIndex: 1,
            name: '正态分布',
            type: 'line',
            data: this.line_data.sort((c,n) => c[0] - n[0]),
            smooth: false,
            showSymbol: false,
            markLine: {
              symbol: 'none',
              data: [
                {
                  name: 'lsl',
                  xAxis: this.normalData.lsl,
                  lineStyle: {
                    color: 'red'
                  },
                  precision: 4,
                  // label: {
                  //   show: false
                  // }
                },{
                  name: 'usl',
                  xAxis: this.normalData.usl,
                  lineStyle: {
                    color: 'red'
                  },
                  precision: 4,
                  // label: {
                  //   show: false
                  // }
                },{
                  name: 'clX',
                  xAxis: this.normalData.clX,
                  lineStyle: {
                    color: 'blue'
                  },
                  precision: 4,
                  // label: {
                  //   show: false
                  // }
                },{
                  name: 'clx+3*sigma',
                  xAxis: this.normalData.clX + 3 * this.normalData.sigma,
                  lineStyle: {
                    color: '#e9a700'
                  },
                  precision: 4,
                  // label: {
                  //   show: false
                  // }
                },{
                  name: 'clx-3*sigma',
                  xAxis: this.normalData.clX - 3 * this.normalData.sigma,
                  lineStyle: {
                    color: '#e9a700'
                  },
                  precision: 4,
                  // label: {
                  //   show: false
                  // }
                }

              ],
              label: {
                distance: [20, 8]
              }
            }
          },
        ]
      }
    }
  },
  methods: {
    fx(sigma, x, avg) {
        let pi = Math.PI
        let v = Math.pow(x - avg, 2) / (2 * Math.pow(sigma,2))
        let exp = Math.exp(-v)
        return (1 / Math.sqrt(2 * pi) * sigma) * exp
    },
    chartInit() {
      this.$nextTick(() => {
        if(!this.chart){
          this.chart = echarts.init(document.getElementById('chart'))
        }
        this.chart && this.chart.setOption(this.option)
      })
    },
    resize () {
      this.chart && this.chart.resize()
    }
  }
}
</script>

<style scoped lang="less">
.NormalChart {
  display: grid;
  grid-template-columns: 1fr 240px;
  height: calc(100vh - 45px - 60px - 112px);
  grid-gap: 20px;
  .total {
    background-color: #f1f1f1;
    border-radius: 5px;
    padding: 20px;
    .item {
      line-height: 30px;
      label {
        font-weight: bold;
      }
      span {
        color: #575757;
      }
    }
  }
}
</style>